const std = @import("std");
const jetzig = @import("jetzig");
const article_service = @import("../service/article_service.zig");

/// 搜索文章
pub fn index(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    const params = req.queryParams() catch return req.render(.bad_request);
    const keyword = params.getT(.string, "keyword") orelse return req.render(.bad_request);
    // std.debug.print("keyword: {s}\n", .{keyword});

    const articles = try article_service.searchArticles(keyword);

    var root = try data.object();
    var arts_array = try data.array();
    for (articles) |art| {
        var art_obj = try data.object();
        try art_obj.put("id", data.integer(art.id));
        try art_obj.put("title", data.string(art.title));
        try art_obj.put("description", data.string(art.description));
        try art_obj.put("content", data.string(art.content));
        try art_obj.put("istop", data.boolean(art.istop == 1));
        try art_obj.put("cate_name", data.string(art.cate_name));
        try art_obj.put("created_at", data.string(art.created_at));

        try arts_array.append(art_obj);
    }
    try root.put("articles", arts_array);
    try root.put("keyword", data.string(keyword));

    return req.render(.ok);
}
